package cn.good.yan.config.security.Filter;

import cn.good.yan.config.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT 登录授权过滤器
 *
 * @author shengren.yan
 * @create 2024/11/3
 */
public class JwtauthencationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {


        String header = request.getHeader(tokenHeader);
        // 获取 tokenHeader配置的请求头，是否存在，并且开头以 tokenHead配置的为开头
        // 正常的请求头的  key是Authorization  value 是  Bearer jwt生产的token令牌
        // 存在
        if (null != header && header.startsWith(tokenHead)) {
            String token = header.substring(tokenHead.length());
            // 从token中获取登录用户名
            String username = jwtTokenUtil.getUserFromToken(token);
            // 存在token，但用户名未登录
            // SecurityContextHolder.getContext().getAuthentication() 这个在Security上下文中获取 用户对象
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                // 登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                // 验证token 是否有效, 有效进行重新设置用户对象
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    // 更新security里的用户信息,
                    // 参数：userDetails 、
                    //     凭证（密码）这里一般是null 、
                    //     权限列表
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                            userDetails,
                            null,
                            userDetails.getAuthorities()
                    );
                    // 重新设置到用户对象里
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }

        }
        // 进行放行
        filterChain.doFilter(request, response);
    }

}
